//
//  FGChatUserModel.m
//  FGChatChatKit
//
//  Created by Henry on 2021/8/27.
//

#import "FGChatUserModel.h"
#import <SDWebImage/SDWebImageDownloader.h>
#import "FGChatHelper.h"
#import "FGResources.h"
#import "FGChatHelper.h"
#import "UIImage+Addtions.h"
#import "UIImage+FGUtil.h"
#import "NSString+FGHash.h"
#import "FGResources.h"
#import "FGPathTool.h"

@implementation FGChatUserModel

- (instancetype)initWithUserId:(NSString *)userId name:(NSString *)name {
    self = [super init];
    if (self) {
        _userId = userId;
        _name = name;
    }
    return self;
}

+ (instancetype)modelWithUserId:(NSString *)userId name:(NSString *)name {
    return [[self alloc] initWithUserId:userId name:name];
}

- (void)configDefaultImage {
    if (_portraitImage) {
        return;
    }
    UIImage *defaultHead = [FGResources getImageFromMessage:@"default_head"];
    if (_userId.length == 0) {
        _portraitImage = defaultHead;
        return;
    }
    NSString *avatarName = [_userId fg_md5String];

    NSString *imagePath = [FGChatHelper pathAvatarImage:avatarName];
    if ([FGPathTool isExistFile:imagePath]) {
        _portraitImage = [UIImage imageWithContentsOfFile:imagePath];
        return;
    }
    
    if (_portrait.length == 0) {
        // 已名称生成
        UIImage *image = [UIImage getImage:_name];
        [[NSFileManager defaultManager] createFileAtPath:imagePath contents:UIImageJPEGRepresentation(image, 1) attributes:nil];
        _portraitImage = image;
        return;
    }
    
    // FIXME: url 需要下载
    NSURL *url = [NSURL URLWithString:_portrait];
    
    [[SDWebImageDownloader sharedDownloader] downloadImageWithURL:url options:SDWebImageDecodeFirstFrameOnly|SDWebImageAllowInvalidSSLCertificates progress:^(NSInteger receivedSize, NSInteger expectedSize, NSURL * _Nullable targetURL) {
        
    } completed:^(UIImage * _Nullable image, NSData * _Nullable data, NSError * _Nullable error, BOOL finished) {
        
        if (error) {
            image = [UIImage getImage:self.name];
        }
        
        [[NSFileManager defaultManager] createFileAtPath:imagePath contents:UIImageJPEGRepresentation(image, 1) attributes:nil];
        self.portraitImage = image;
        
    }];
}

- (NSString *)debugDescription {
    return [NSString stringWithFormat:@"FGChatUserModel: userId=%@, name=%@", self.userId, self.name];
}

@end
